package com.ucar.ui.main;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.ucar.R;
import com.ucar.bean.AD;
import com.ucar.ui.base.BaseSlidingFragmentActivity;
import com.ucar.ui.main.MainFragment.MainFragCallBack;

/**
 * 主界面
 * @author moon
 *
 */
public class MainActivity extends BaseSlidingFragmentActivity implements MainFragCallBack
{
	private SlidingMenu mSlidingMenu;
	private MenuFragment menuFragment;
	
	private long firstClickTime = 0;
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate( savedInstanceState );
		setBaseTitleContent( R.layout.activity_main, R.string.app_name );
		initSlidingMenu();
	}
	

	@Override
	public void onInit() {
		setLeftImage( R.drawable.icon_left_menu, 
		new OnClickListener() {
			@Override
			public void onClick(View v) {
				showLeftMenu();
			}
		});
	}

	@Override
	public void onFindViews() {
	}

	@Override
	public void onInitViewData() {
		
	}

	@Override
	public void onBindListener() {
		
	}
	
	// 初始化左侧菜单
	private void initSlidingMenu() 
	{
		mSlidingMenu = getSlidingMenu();
		
		setBehindContentView( R.layout.layout_main_left );// 设置左边的菜单布局

		menuFragment = new MenuFragment();
		MainFragment mainFragment = new MainFragment();
		mainFragment.setmCallBack( this );
		
		addFragment( menuFragment, R.id.fragment_main_left, "menu" );
		addFragment( mainFragment, R.id.fragment_content, "main" );
		mSlidingMenu.setBehindOffsetRes( R.dimen.slidingmenu_offset );
		mSlidingMenu.setFadeEnabled(false);
		mSlidingMenu.setFadeDegree(0.25f);
		mSlidingMenu.setMode(SlidingMenu.LEFT);
		mSlidingMenu.setBackgroundColor( 0xFFFFFF );
	}
	
	public void showLeftMenu() 
	{
		if( null != mSlidingMenu ) 
		{
			mSlidingMenu.showMenu(true);
		}
	}

	protected void addFragment(Fragment fragment, int resId, String tag) 
    {
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		transaction.replace(resId, fragment, tag);
		transaction.commit();
	}


	@Override
	public void showAd(AD ad) 
	{
		menuFragment.showAd( ad );
	}
	
	@Override
	public void onBackPressed() {
		long secondTime = System.currentTimeMillis();
		if (secondTime - firstClickTime > 2000) {
			showToast("再按一次退出程序...");
			firstClickTime = secondTime;
			return;
		} else {
			finish();
		}
	}
}
